# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>

from gettext import gettext as _
from argparse import ArgumentParser, Action

from excavator.constants import BANNER


# 打印带横幅的版本号
class _VersionAction(Action):
    def __init__(self,
                 option_strings,
                 dest,
                 default=None,
                 help="display version and banner, then exit"):
        super(_VersionAction, self).__init__(
            option_strings=option_strings,
            dest=dest,
            default=default,
            nargs=0,
            help=help)

    def __call__(self, parser, namespace, values, option_string=None):
        print(BANNER)
        exit(0)


class ExcavatorArgParser(ArgumentParser):
    def __init__(self, **kwargs):
        super(ExcavatorArgParser, self).__init__(**kwargs)
        self.prog = kwargs.get("prog", None) or \
                    'excavator'
        self.usage = kwargs.get("usage", None) or \
                     '%(prog)s command [options]'
        self.description = kwargs.get("description", None) or \
                           'Excavator is an OS conversion tool. ' \
                           'Use Excavator to upgrade opencloudos from 8 to 9. '
        self.epilog = kwargs.get("epilog", None) or \
                      'Use %(prog)s command --help to read about a specific command  usage.'
        self.add_base_options()
        self.option_title = "General options"
        self._optionals.title = self.option_title
        self.commands_title = 'Main commands'
        self.subparsers = self.add_subparsers(
            title=self.commands_title,
            # title='',
            # help='sub-command help',
            # help="",
            dest='subcommand',
            # required=True,
            metavar=''
        )

    def add_base_options(self):
        self.add_argument('-v', '--version', action=_VersionAction)

    def add_sub_command(self, cmd):
        parser_s = self.subparsers.add_parser(cmd.name, prog=self.prog,
                                              description=cmd.summary,
                                              usage='%(prog)s {} [options]'.format(cmd.name),
                                              epilog=" ",
                                              help=cmd.description)
        parser_s._optionals.title = _("{} options".format(cmd.name.capitalize()))

        cmd.set_arg_parser(parser_s)

        parser_s.set_defaults(func=cmd.run)

    def format_help(self):
        formatter = self._get_formatter()

        # usage
        formatter.add_usage(self.usage, self._actions,
                            self._mutually_exclusive_groups)

        # description
        formatter.add_text(self.description)

        # positionals, optionals and user-defined groups
        for action_group in self._action_groups:
            # ignore subcommand  section in subcommand
            if action_group.title == self.commands_title and \
                    "command" not in self.usage:
                continue
            group_actions = []
            if action_group.title != self.option_title:
                for action in action_group._group_actions:
                    # ignore help and version option in subcommand
                    if action.dest not in ["help", "version"]:
                        group_actions.append(action)
            else:
                group_actions = action_group._group_actions
            formatter.start_section(action_group.title)
            formatter.add_text(action_group.description)
            formatter.add_arguments(group_actions)

            formatter.end_section()

        # epilog
        formatter.add_text(self.epilog)

        # determine help from format abov
        return formatter.format_help()
